<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div v-auth-dir="`park:building:list`" class="search-container">
      <div class="search-label">楼宇名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" @clear="doSearch" />
      <el-button v-auth-dir="`park:building:query`" type="primary" :disabled="search" @click="doSearch">查询</el-button>
    </div>
    <div class="btn-container">
      <el-button v-auth-dir="`park:building:add_edit`" type="primary" @click="addBuildingFn()">添加楼宇</el-button>
      <el-button v-auth-dir="`park:building:add_edit`" type="success" plain @click="dowlondFn">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table
        :data="buildingList"
        style="width: 100%"
      >
        <el-table-column
          type="index"
          label="序号"
        />
        <el-table-column
          label="楼宇名称"
          width="180"
          prop="name"
        />
        <el-table-column
          label="层数"
          prop="floors"
        />
        <el-table-column
          label="在管面积(m²)"
          width="120"
          prop="area"
        />
        <el-table-column
          label="物业费(元/m²)"
          width="120"
          prop="propertyFeePrice"
        />
        <el-table-column
          label="状态"
          prop="status"
        >
          <template #default="scope">
            {{ statusMap[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
        >
          <template #default="scope">
            <el-button
              v-auth-dir="`park:building:add_edit`"
              size="mini"
              type="text"
              @click="addBuildingFn(scope.row)"
            >编辑</el-button>
            <el-button
              v-auth-dir="`park:building:remove`"
              size="mini"
              type="text"
              @click="delBuildingFn(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :page-size="params.pageSize"
        @current-change="pageChangeFn"
      />
    </div>
    <!-- 添加楼宇弹框 -->
    <el-dialog
      :title="title"
      :visible="dialogVisible"
      width="580px"
      @close="closeBuildingFn"
    >
      <div class="form-container">
        <el-form ref="addForm" :model="addForm" :rules="addFormRules">
          <el-form-item label="楼宇名称" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="楼宇层数" prop="floors">
            <el-input v-model="addForm.floors" />
          </el-form-item>
          <el-form-item label="在管面积" prop="area">
            <el-input v-model="addForm.area" />
          </el-form-item>
          <el-form-item label="物业费" prop="propertyFeePrice">
            <el-input v-model="addForm.propertyFeePrice" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="addBuildingMsgFn">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getBuildingListAPI, addBuildingAPI, editBuildingAPI, delBuildingAPI } from '@/apis/building'
import { utils, writeFileXLSX } from 'xlsx'
export default {
  name: 'Building',
  data() {
    return {
      params: {
        name: '', // 楼宇名称模糊查询
        page: 1, // 当前页码
        pageSize: 10 // 每页大小
      },
      buildingList: [], // 楼宇列表
      statusMap: {
        0: '空闲中',
        1: '租赁中'
      },
      total: 0, // 分页总条数
      dialogVisible: false, // 控制弹窗
      addForm: {
        name: '',
        floors: null,
        area: null,
        propertyFeePrice: null
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入楼宇名称', trigger: 'blur' }
        ],
        floors: [
          { required: true, message: '请输入楼宇层数', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '请输入楼宇面积', trigger: 'blur' }
        ],
        propertyFeePrice: [
          { required: true, message: '请输入楼宇物业费', trigger: 'blur' }
        ]
      },
      title: '' // 窗口的标题
    }
  },
  computed: {
    search() {
      if (this.params.name) {
        return false
      } else {
        return true
      }
    }
  },
  created() {
  },
  mounted() {
    this.getBuildingList()
  },
  methods: {
    // 获取楼宇列表
    async getBuildingList() {
      if (!this.params.name) {
        delete this.params.name
      }
      const res = await getBuildingListAPI(this.params)
      console.log(res)
      this.buildingList = res.data.rows
      this.total = res.data.total
    },
    // 点击分页功能
    pageChangeFn(nextPage) {
      // console.log(page)
      this.params.page = nextPage
      this.getBuildingList()
    },
    // 搜索楼宇
    doSearch() {
      this.params.page = 1
      this.getBuildingList()
    },
    // 添加楼宇-窗口
    async addBuildingFn(row) {
      if (!row) {
        this.addForm.name = ''
        this.addForm.floors = null
        this.addForm.area = null
        this.addForm.propertyFeePrice = null

        this.title = '添加楼宇'
      } else {
        // console.log(id)
        // const res = await queryBuildingAPI(id)
        // console.log(res)
        // this.addForm = res.data[0]
        const { id, name, floors, area, propertyFeePrice } = row
        this.addForm = {
          id, name, floors, area, propertyFeePrice
        }
        this.title = '编辑楼宇'
        // this.addForm = row
      }
      this.dialogVisible = true
      // console.log(row)
    },
    // 关闭弹窗
    async closeBuildingFn() {
      this.$refs.addForm.resetFields()
      // if (this.title === '编辑楼宇') {
      // }
      this.dialogVisible = false
    },
    // 添加楼宇信息
    async addBuildingMsgFn() {
      // console.log(id)
      let res = {}
      if (this.title === '添加楼宇') {
        await this.$refs.addForm.validate()
        res = await addBuildingAPI(this.addForm)
      } else {
        res = await editBuildingAPI(this.addForm)
      }
      this.$message({
        type: 'success',
        message: res.msg
      })
      this.getBuildingList()
      this.dialogVisible = false
      // console.log(res)
    },
    // 删除指定楼宇信息
    async delBuildingFn(id) {
      this.$confirm('确定要移除当前楼宇信息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delBuildingAPI(id)
        console.log(res)
        this.getBuildingList()
        this.$message({
          type: 'success',
          message: res.msg
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 导出execl文件
    async dowlondFn() {
      // TODO======>下载方式，下载当前页，下载全部
      const res = await getBuildingListAPI(this.params)
      const tableHeader = ['name', 'floors', 'area', 'propertyFeePrice', 'status']
      const sheetData = res.data.rows.map((item) => {
        const obj = {}
        tableHeader.forEach(key => {
          obj[key] = item[key]
        })
        return obj
      })
      // console.log(sheetData)
      // 创建一个工作表
      const worksheet = utils.json_to_sheet(sheetData)
      const workbook = utils.book_new()
      utils.book_append_sheet(workbook, worksheet, 'Data')
      utils.sheet_add_aoa(worksheet, [['楼宇名称', '楼层', '在管面积（m²）', '物业费（m²）', '状态']], { origin: 'A1' })
      writeFileXLSX(workbook, '楼宇信息列表.xlsx')
    }
  }
}

</script>

<style lang="scss" scoped>
.btn-container{
  margin-top: 15px;
}
  .page-container{
    padding:4px 0px;
    text-align: right;
  }
.department-container{
  padding:10px;
}
.search-container{
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237,237,237,.9);;
  padding-bottom: 20px;
  .search-label{
    width:100px;
  }
  .search-main{
    width: 220px;
    margin-right: 10px;
  }
}
</style>
